import fs from "node:fs/promises";
import path from "node:path";
import { readDocSections, searchDocs } from "./doc-reader";
import { readBlueprint, filterFigmaData, extractDesignIntent, writeJsonFile, writeYamlFile } from "./data-processor";
import { validateThreeLayerArchitecture, summarizeCoverage } from "./validator";

const WORKFLOW_ROOT = path.resolve(__dirname, "..", "..");
const TOOLS_INDEX_PATH = path.join(WORKFLOW_ROOT, "tools-index.json");

export interface SearchToolsOptions {
  phase?: number | string;
  keyword?: string;
  limit?: number;
}

export interface ToolDescriptor {
  name: string;
  description: string;
  entry: string;
  params?: Record<string, string>;
  phaseHints?: string[];
  examples?: string[];
}

function normalisePhase(value?: number | string): string | undefined {
  if (value === undefined || value === null) {
    return undefined;
  }
  const asString = value.toString().toLowerCase();
  return asString.startsWith("phase") ? asString : `phase${asString}`;
}

export async function searchTools(options: SearchToolsOptions): Promise<ToolDescriptor[]> {
  const { phase, keyword, limit = 10 } = options;
  const phaseKey = normalisePhase(phase);
  const raw = await fs.readFile(TOOLS_INDEX_PATH, "utf-8");
  const entries = JSON.parse(raw) as ToolDescriptor[];
  const hits: ToolDescriptor[] = [];
  const needle = keyword?.toLowerCase();

  for (const entry of entries) {
    if (phaseKey && entry.phaseHints && !entry.phaseHints.includes(phaseKey)) {
      continue;
    }
    if (needle) {
      const haystack = `${entry.name} ${entry.description}`.toLowerCase();
      if (!haystack.includes(needle)) {
        continue;
      }
    }
    hits.push(entry);
    if (hits.length >= limit) {
      break;
    }
  }

  return hits;
}

export {
  readDocSections,
  searchDocs,
  readBlueprint,
  filterFigmaData,
  extractDesignIntent,
  validateThreeLayerArchitecture,
  summarizeCoverage,
  writeJsonFile,
  writeYamlFile,
};
